﻿using DearlerPlatform.Domain;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DearlerPlatform.Extensions
{
    //注册仓储
    public static class RepositoryRegisterExtensions
    {
        /// <summary>
        /// 注册仓储的依赖注入,新建一个IServiceCollection的扩展方法注册
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection RepositoryRegister(this IServiceCollection services)
        {
            var asmCore = Assembly.Load("DearlerPlatform.Core");
            //获取有一个泛型参数的泛型类型叫Repository的Type
            //其实就是获取Core项目的Repository类
            var implementationType = asmCore.GetTypes().FirstOrDefault(m => m.Name == "Repository`1");
            //获取接口
            //其实就是获取Core项目的IRepository接口
            //var interfaceType = implementationType.GetInterface("IRepository`1");
            var interfaceType = implementationType.GetInterface("IRepository`1").GetGenericTypeDefinition();
            services.AddTransient(interfaceType, implementationType);
            return services;
        }

        public static IServiceCollection ServiceRegister(this IServiceCollection services)
        {
            var asmCore = Assembly.Load("DearlerPlatform.Service");
            var implementationTypes = asmCore.GetTypes().Where(
                m => m.IsAssignableTo(typeof(IocTag)) && 
                !m.IsAbstract &&
                !m.IsInterface 
                );
            foreach(var implementationType in implementationTypes)
            {
                var interfaceType = implementationType.GetInterfaces().Where(m => m != typeof(IocTag));
                //services.AddTransient(interfaceType, implementationType);
            }
            return services;
        }
    }
}
